package cn.uin.domain.auth.service.user.register.strategy;

import cn.uin.domain.auth.adapter.port.IAuthNotificationPort;
import cn.uin.domain.auth.adapter.repository.IAuthRepository;
import cn.uin.domain.auth.model.entity.HomeUserEntity;
import cn.uin.domain.auth.model.entity.HomeUserRegisterEntity;
import cn.uin.domain.auth.model.valobj.RegisterTypeEnum;
import cn.uin.domain.auth.service.user.register.AbstractRegisterService;
import cn.uin.domain.auth.service.user.register.factory.RegisterStrategyFactory;
import cn.uin.types.common.RedisConstants;
import cn.uin.types.enums.ResponseCode;
import cn.uin.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * @ClassName PwdRegisterService
 * @Description:邮箱注册策略
 * @Author: Administrator
 * @CreateDate: 2025/10/22 10:13
 * @Version: 1.0
 */
@Slf4j
@Service("EmailRegister")
public class EmailRegisterService extends AbstractRegisterService implements ApplicationRunner {

	@Resource
	private IAuthRepository iAuthRepository;

	@Override
	protected void checkUser(HomeUserRegisterEntity homeUserRegisterEntity) {
		if (StringUtils.isEmpty(homeUserRegisterEntity.getEmail()) ||
				StringUtils.isEmpty(homeUserRegisterEntity.getCode())) {
			throw new AppException(ResponseCode.C0002.getCode(), ResponseCode.C0002.getInfo());
		}
		HomeUserEntity homeUserEntity = iAuthRepository.queryUserByUserEmail(homeUserRegisterEntity.getEmail());
		if (!ObjectUtils.isEmpty(homeUserEntity)) {
			throw new AppException(ResponseCode.A0001.getCode(), ResponseCode.A0001.getInfo());
		}
		// 校验验证码是否正确
		boolean emailCodeFlag = iAuthRepository.checkCode(RedisConstants.EMAIL_REGISTER_CODE + homeUserRegisterEntity.getEmail(),
				homeUserRegisterEntity.getCode());
		if (!emailCodeFlag) {
			throw new AppException(ResponseCode.A0006.getCode(), ResponseCode.A0006.getInfo());
		}
	}

	@Override
	protected HomeUserEntity doRegister(HomeUserRegisterEntity homeUserRegisterEntity) {
		homeUserRegisterEntity.setType(RegisterTypeEnum.EMAIL.getCode());
		homeUserRegisterEntity.setUsername(homeUserRegisterEntity.buildDefaultUsername());
		iAuthRepository.saveUser(homeUserRegisterEntity);
		return HomeUserEntity.builder()
				.username(homeUserRegisterEntity.getUsername())
				.email(homeUserRegisterEntity.getEmail())
				.phone(homeUserRegisterEntity.getPhone())
				.build();
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		RegisterStrategyFactory.addStrategy("EmailRegister", this);
	}
}
